package com.time.company.components.compose.city;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.time.company.R;
import com.time.company.app.AddressManager;
import com.time.company.base.BaseActivity;
import com.time.company.base.BaseFragment;
import com.time.company.servermodel.BasicBean;
import com.time.company.servermodel.compose.CityList;
import com.time.company.utils.NetWorkUtils;
import com.time.company.utils.ToastUtils;
import com.time.company.webserver.helper.WebServerManager;
import com.time.company.webserver.request.BasicRequest;
import com.time.company.webserver.request.requestsParamters.ComposeParameters;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

import java.util.ArrayList;
import java.util.List;

/**
 * 城市列表 -- 筛选
 * Created by Bing on 2017/11/16.
 * E-mail is tx16bing@163.com
 */

public class CityListActivity extends BaseActivity implements View.OnClickListener {

    private Request request;
    private static final int GET_CITY_LIST_WHAT = 99;

    public static final int REQUEST_CODE_PICK_CITY = 2333;
    public static final String KEY_PICKED_CITY = "picked_city";

    private ListView lvAllCity;
    private ListView lvResult;
    private SideLetterBar mLetterBar;
    private EditText etSearch;
    private ImageView ivClear;
    private TextView tvCancel;

    private CityListAdapter mCityAdapter;
    private ResultListAdapter mResultAdapter;
    private List<CityList.City> mAllCities;

    private AMapLocationClient locationRequest;

    public static void start(Activity activity, int requestCode) {
        Intent intent = new Intent(activity, CityListActivity.class);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void start(BaseFragment fragment, int requestCode) {
        Intent intent = new Intent(fragment.mContext, CityListActivity.class);
        fragment.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city_list);
        assignViews();
        cityListRequest();

    }

    private void assignViews() {
        lvAllCity = findView(R.id.lv_all_city);

        TextView overlay = findView(R.id.tv_letter_overlay);
        mLetterBar = findView(R.id.side_letter_bar);
        mLetterBar.setOverlay(overlay);
        mLetterBar.setOnLetterChangedListener(new SideLetterBar.OnLetterChangedListener() {
            @Override
            public void onLetterChanged(String letter) {
                // 根据字母获取列表的位置
                int position = mCityAdapter.getLetterPosition(letter);
                // 将列表移动到指定的Position处
                lvAllCity.setSelection(position);
            }
        });

        etSearch = findView(R.id.et_search);
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = s.toString();
                if (TextUtils.isEmpty(keyword)) {
                    ivClear.setVisibility(View.GONE);
                    lvResult.setVisibility(View.GONE);
                } else {
                    ivClear.setVisibility(View.VISIBLE);
                    lvResult.setVisibility(View.VISIBLE);
                    List<CityList.City> result = filterData(keyword);
                    if (result == null || result.size() == 0) {
                        ToastUtils.showShort("当前没有符合搜索的地点");
                    } else {
                        ToastUtils.showShort("Size " + result.size());
                        mResultAdapter.changeData(result);
                    }
                }
            }
        });

        lvResult = findView(R.id.lv_search_result);
        lvResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                click(mResultAdapter.getItem(position).getCity());
            }
        });

        ivClear = findView(R.id.iv_search_clear);
        tvCancel = findView(R.id.tv_search_cancel);
        ivClear.setOnClickListener(this);
        tvCancel.setOnClickListener(this);
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     * @param filterStr
     */
    private List<CityList.City> filterData(String filterStr) {
        List<CityList.City> filterDateList = new ArrayList<>();
        CharacterParser characterParser = new CharacterParser();
        if (!TextUtils.isEmpty(filterStr)) {
            filterDateList.clear();
            for (CityList.City city : mAllCities) {
                String name = city.getCity();
                if (name.toUpperCase().indexOf(
                        filterStr.toString().toUpperCase()) != -1
                        || characterParser.getSelling(name).toUpperCase()
                        .startsWith(filterStr.toString().toUpperCase())) {
                    filterDateList.add(city);
                }
            }
        }

        return filterDateList;

    }

    @Override
    public void onClick(View v) {
       switch (v.getId()){
           case R.id.iv_search_clear:
               etSearch.setText("");
               ivClear.setVisibility(View.GONE);
               lvResult.setVisibility(View.GONE);
               break;

           case R.id.tv_search_cancel:
               finish();
               break;

           default:
               break;
       }
    }

    private void click(String city){
        Intent data = new Intent();
        data.putExtra(KEY_PICKED_CITY, city);
        setResult(RESULT_OK, data);
        finish();
    }

    /**
     * 获取地点列表
     */
    private void cityListRequest() {
        if (NetWorkUtils.isNetAvailable(application)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            ComposeParameters parameters = new ComposeParameters();
            parameters.setCommand(application.getString(R.string.command_getCityList));
            parameters.setUserId(application.getAccount());
            request.add(application.getString(R.string.command), parameters.getCommand());
            request.add(application.getString(R.string.platform), parameters.getPlatform());
            request.add(application.getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this,
                    GET_CITY_LIST_WHAT, true, true, true);
        } else {
            ToastUtils.showShort(application.getString(R.string.network_error));
        }
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {
        BasicBean basicBean = response.get();
        if (basicBean== null) return;

        if (basicBean.isSuccess()){
            CityList cityList = basicBean.parseData(CityList.class);
            if (cityList == null) return;
            List<CityList.City> cities = cityList.getCities();
            if (null != cities){
                mAllCities = cities;
                mCityAdapter = new CityListAdapter(this, mAllCities);
                mCityAdapter.setOnCityClickListener(new CityListAdapter.OnCityClickListener() {
                    @Override
                    public void onCityClick(String name) {
                        click(name);
                    }

                    @Override
                    public void onLocateClick() {
                        mCityAdapter.updateLocateState(LocateState.LOCATING, "定位中...");
                        locationRequest.startLocation();
                    }
                });
                lvAllCity.setAdapter(mCityAdapter);

                mResultAdapter = new ResultListAdapter(this, null);
                lvResult.setAdapter(mResultAdapter);
                createLocationRequest();
            }
        }else {
            ToastUtils.showShort(basicBean.getMsg());
        }

    }

    protected void createLocationRequest() {

        // 初始化请求
        locationRequest = new AMapLocationClient(getApplicationContext());

        // 设置回调监听
        locationRequest.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation == null || aMapLocation.getErrorCode() != 0) {
                    ToastUtils.showShort("定位失败");
                    mCityAdapter.updateLocateState(LocateState.FAILED, "定位失败");
                    return;
                }

                Logger.i("Current user postion is lat : " + aMapLocation.getLatitude() +
                        " and lon : " + aMapLocation.getLongitude());
                // TODO: 2017/11/16
                mCityAdapter.updateLocateState(LocateState.SUCCESS, aMapLocation.getCity());
            }
        });

        // 初始化参数集
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        // 高精度定位模式，省电模式， 仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        // 是否返回地址信息
        mLocationOption.setNeedAddress(true);
        // 设置重定位时间间隔
        mLocationOption.setInterval(5000);
        mLocationOption.setOnceLocation(true);
        // 设置参数集
        locationRequest.setLocationOption(mLocationOption);
        locationRequest.startLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        locationRequest.stopLocation();
    }

}
